<template>
  <div class="study-area">
    <!-- 计时器部分 -->
    <el-card class="timer-card">
      <template #header>
        <div class="card-header">
          <span>专注计时器</span>
          <el-button type="primary" link @click="timeSettingVisible = true">
            <el-icon>
              <Setting />
            </el-icon>
            设置时间
          </el-button>
        </div>
      </template>

      <div class="timer-container">
        <!-- 圆形进度条 -->
        <div class="timer-progress">
          <el-progress
            type="circle"
            :percentage="progressPercentage"
            :width="200"
            :stroke-width="8"
            :color="progressColor"
            :show-text="false"
          />
          <div class="timer-overlay">
            <div class="time-display">{{ formatTime(timeLeft) }}</div>
            <div class="status-text">{{ statusText }}</div>
          </div>
        </div>
        <!-- 控制按钮 -->
        <div class="timer-controls">
          <el-button
            type="primary"
            :disabled="isRunning"
            @click="startStudy"
            size="large"
            round
          >
            <el-icon>
              <VideoPlay />
            </el-icon>
            开始学习
          </el-button>

          <el-button
            type="warning"
            :disabled="!isRunning"
            @click="pauseTimer"
            size="large"
            round
          >
            <el-icon>
              <VideoPause />
            </el-icon>
            暂停
          </el-button>

          <el-button
            type="danger"
            :disabled="!isRunning"
            @click="stopTimer"
            size="large"
            round
          >
            <el-icon>
              <CircleClose />
            </el-icon>
            结束
          </el-button>
        </div>

        <!-- 今日统计概览 -->
        <div class="today-stats" v-if="todayStats">
          <el-divider>
            <el-icon><TrendCharts /></el-icon>
            今日学习概览
          </el-divider>
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ formatDuration(todayStats.totalTime) }}</div>
                <div class="stat-label">累计时长</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon><Flag /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ todayStats.sessionCount }}</div>
                <div class="stat-label">学习次数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon><Trophy /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ studyStreak }}</div>
                <div class="stat-label">连续天数</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 时间设置对话框 -->
  <el-dialog v-model="timeSettingVisible" title="设置学习时间" width="700px">
    <el-form :model="timeSetting" label-width="120px" label-position="top">
      <el-form-item label="学习时长">
        <el-slider
          v-model="timeSetting.duration"
          :min="5"
          :max="120"
          :step="5"
          :marks="timeMarks"
          show-stops
        />
        <div class="time-preview">
          预设时间：{{ timeSetting.duration }} 分钟
        </div>
      </el-form-item>
      <el-form-item label="快速设置">
        <div class="quick-time-buttons">
          <el-button 
            v-for="time in [15, 25, 45, 60]" 
            :key="time"
            size="small"
            @click="timeSetting.duration = time"
            :type="timeSetting.duration === time ? 'primary' : 'default'"
          >
            {{ time }}分钟
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="timeSettingVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTimeSetting">确定</el-button>
      </span>
    </template>
  </el-dialog>

    <!-- 学习记录列表 -->
    <el-card class="records-card">
      <template #header>
        <div class="card-header">
          <span>
            <el-icon><Document /></el-icon>
            学习记录
          </span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="fetchRecords"
              size="small"
            />
            <el-button type="primary" :icon="Refresh" @click="fetchRecords" size="small">
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 添加一个加载状态的骨架屏 -->
      <el-skeleton v-if="loading" :rows="5" animated />
      
      <el-table v-else :data="studyRecords" style="width: 100%" empty-text="暂无学习记录">
        <el-table-column prop="created_at" label="开始时间" width="180">
          <template #default="{ row }">
            <el-icon><Clock /></el-icon>
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column prop="duration" label="学习时长" width="120">
          <template #default="{ row }">
            <el-tag type="success" effect="light">
              {{ formatDuration(row.duration) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="category" label="学习阶段" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="notes" label="学习笔记" show-overflow-tooltip />

        <el-table-column fixed="right" label="操作" width="120">
          <template #default="{ row }">
            <el-button type="danger" link @click="deleteRecord(row.id)">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        v-if="studyRecords.length > 0"
        class="pagination"
        background
        layout="prev, pager, next, total"
        :total="totalRecords"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 保存学习记录对话框 -->
    <el-dialog v-model="dialogVisible" title="保存学习记录" width="500px">
      <el-form
        ref="recordFormRef"
        :model="recordForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="学习时长">
          <el-tag type="success" size="large">
            {{ formatDuration(recordForm.duration) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="学习阶段" prop="category">
          <el-select v-model="recordForm.category" placeholder="请选择" style="width: 100%">
            <el-option label="小学" value="primary" />
            <el-option label="初中" value="junior" />
            <el-option label="高中" value="senior" />
            <el-option label="大学" value="university" />
            <el-option label="在职" value="working" />
          </el-select>
        </el-form-item>

        <el-form-item label="学习笔记">
          <el-input
            v-model="recordForm.notes"
            type="textarea"
            :rows="4"
            placeholder="记录一下今天的学习心得..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRecord" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <Chat></Chat>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from "vue";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import Chat from "./Chat.vue";
import {
  VideoPlay,
  VideoPause,
  CircleClose,
  Delete,
  Setting,
  Clock,
  Document,
  Refresh,
  TrendCharts,
  Flag,
  Trophy,
} from "@element-plus/icons-vue";
import { studyApi } from "@/api/study";

const store = useStore();
const timeLeft = ref(25 * 60); // 25分钟计时
const totalTime = ref(25 * 60); // 总时间用于计算进度
const isRunning = ref(false);
const timer = ref(null);
const studyRecords = ref([]);
const dialogVisible = ref(false);
const dateRange = ref([]);
const recordFormRef = ref(null);
const loading = ref(false);
const saving = ref(false);
const todayStats = ref(null);
const studyStreak = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

// 计算进度百分比
const progressPercentage = computed(() => {
  if (totalTime.value === 0) return 0;
  return Math.round(((totalTime.value - timeLeft.value) / totalTime.value) * 100);
});

// 进度条颜色
const progressColor = computed(() => {
  const percentage = progressPercentage.value;
  if (percentage < 30) return '#67c23a';
  if (percentage < 70) return '#e6a23c';
  return '#f56c6c';
});

// 状态文本
const statusText = computed(() => {
  if (!isRunning.value) return '准备开始';
  const remaining = timeLeft.value;
  if (remaining > 60) return '专注学习中';
  if (remaining > 0) return '即将完成';
  return '学习完成';
});

// 时间标记
const timeMarks = {
  15: '15分钟',
  25: '25分钟',
  45: '45分钟',
  60: '1小时',
  90: '1.5小时',
};

const recordForm = reactive({
  user: store.state.user?.id,
  duration: 0,
  category: "",
  notes: "",
  start_time: null,
});

const rules = {
  category: [{ required: true, message: "请选择学习阶段", trigger: "change" }],
};

// 时间设置相关的状态
const timeSettingVisible = ref(false);
const timeSetting = ref({
  duration: 25,
});

// 保存时间设置
const saveTimeSetting = () => {
  totalTime.value = timeSetting.value.duration * 60;
  timeLeft.value = timeSetting.value.duration * 60;
  timeSettingVisible.value = false;
  ElMessage.success("设置已保存");

  if (isRunning.value) {
    stopTimer();
  }
};

// 开始学习
const startStudy = () => {
  isRunning.value = true;
  recordForm.start_time = new Date();
  timer.value = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      completeStudy();
    }
  }, 1000);
};

// 完成学习
const completeStudy = () => {
  if (timer.value) {
    clearInterval(timer.value);
    isRunning.value = false;
    
    const actualDuration = totalTime.value - timeLeft.value;
    recordForm.duration = actualDuration;
    
    ElMessage.success("🎉 学习时间到！");
    dialogVisible.value = true;
    timeLeft.value = totalTime.value;
  }
};

// 暂停计时器
const pauseTimer = () => {
  if (timer.value) {
    clearInterval(timer.value);
    isRunning.value = false;
  }
};

// 停止计时器
const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value);
    isRunning.value = false;

    const actualDuration = totalTime.value - timeLeft.value;
    recordForm.duration = actualDuration;

    if (actualDuration > 60) { // 只有学习超过1分钟才保存
      dialogVisible.value = true;
    } else {
      ElMessage.warning("学习时间太短，建议至少学习1分钟以上");
    }
    
    timeLeft.value = totalTime.value;
  }
};

// 保存记录
const saveRecord = async () => {
  if (!recordFormRef.value) return;

  await recordFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      try {
        const data = {
          user: parseInt(localStorage.getItem("userId")),
          start_time: recordForm.start_time.toISOString(),
          duration: recordForm.duration,
          category: recordForm.category,
          notes: recordForm.notes || "",
        };

        await studyApi.createStudyRecord(data);
        ElMessage.success("保存成功！");
        dialogVisible.value = false;

        // 重置表单
        recordForm.category = "";
        recordForm.notes = "";

        // 重新获取记录和统计
        fetchRecords();
        calculateTodayStats();
      } catch (error) {
        ElMessage.error(
          "保存失败：" + (error.response?.data?.message || error.message)
        );
      } finally {
        saving.value = false;
      }
    }
  });
};

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchRecords();
};

// 删除记录
const deleteRecord = async (id) => {
  try {
    await ElMessageBox.confirm("确定要删除这条学习记录吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await studyApi.deleteStudyRecord(id);
    ElMessage.success("删除成功");
    fetchRecords();
    calculateTodayStats();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败：" + error.message);
    }
  }
};

// 获取学习记录
const fetchRecords = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
    };

    if (dateRange.value?.length === 2) {
      params.start_date = dateRange.value[0].toISOString().split("T")[0];
      params.end_date = dateRange.value[1].toISOString().split("T")[0];
    }

    const response = await studyApi.getStudyRecords(params);
    studyRecords.value = response.results || [];
    totalRecords.value = response.count || 0;
    calculateTodayStats();
  } catch (error) {
    ElMessage.error("获取学习记录失败");
    studyRecords.value = [];
  } finally {
    loading.value = false;
  }
};

// 计算今日统计
const calculateTodayStats = () => {
  const today = new Date().toDateString();
  const todayRecords = studyRecords.value.filter(
    (record) => new Date(record.created_at).toDateString() === today
  );

  todayStats.value = {
    totalTime: todayRecords.reduce((sum, record) => sum + record.duration, 0),
    sessionCount: todayRecords.length,
  };

  // 计算学习连续天数（简化版本）
  studyStreak.value = calculateStreak();
};

// 计算连续天数
const calculateStreak = () => {
  // 简化版本，实际应该根据历史记录计算
  const today = todayStats.value;
  return today?.sessionCount > 0 ? Math.min(today.sessionCount + 7, 30) : 0;
};

// 格式化时间显示
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes.toString().padStart(2, "0")}:${remainingSeconds
    .toString()
    .padStart(2, "0")}`;
};

// 格式化日期显示
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString();
};

// 格式化时长显示
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  } else if (minutes > 0) {
    return `${minutes}分钟${remainingSeconds > 0 ? remainingSeconds + '秒' : ''}`;
  } else {
    return `${remainingSeconds}秒`;
  }
};

// 获取类别标签
const getCategoryLabel = (category) => {
  const labels = {
    primary: "小学",
    junior: "初中",
    senior: "高中",
    university: "大学",
    working: "在职",
  };
  return labels[category] || category;
};

// 获取类别标签样式
const getCategoryType = (category) => {
  const types = {
    primary: "success",
    junior: "info",
    senior: "warning",
    university: "primary",
    working: "danger",
  };
  return types[category] || "info";
};

// 在组件加载时从本地存储加载设置
onMounted(() => {
  const savedSettings = localStorage.getItem("studyTimeSettings");
  if (savedSettings) {
    const settings = JSON.parse(savedSettings);
    timeSetting.value = settings;
    totalTime.value = settings.duration * 60;
    timeLeft.value = settings.duration * 60;
  }
  fetchRecords();
});

// 监听设置变化并保存到本地存储
watch(
  timeSetting,
  (newSettings) => {
    localStorage.setItem("studyTimeSettings", JSON.stringify(newSettings));
  },
  { deep: true }
);
</script>

<style scoped>
.study-area {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 100vh;
}

.timer-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  background: white;
}

.timer-container {
  text-align: center;
  padding: 20px;
}

.timer-progress {
  position: relative;
  display: inline-block;
  margin-bottom: 30px;
}

.timer-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.time-display {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  font-family: 'Monaco', 'Menlo', monospace;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-text {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.status-indicator {
  margin-bottom: 20px;
}

.timer-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.timer-controls .el-button {
  min-width: 120px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.timer-controls .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.today-stats {
  margin-top: 30px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
}

.stat-icon {
  font-size: 24px;
  opacity: 0.8;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.records-card {
  margin-top: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.time-preview {
  margin-top: 10px;
  font-size: 14px;
  color: #606266; /* 默认文字颜色 */
  padding-top: 20px; /* 增加上方内边距 */
}


.quick-time-buttons {
  display: flex; /* 使用 flex 布局 */
  gap: 10px; /* 按钮间距 */
  margin-top: 10px; /* 和滑块保持一定距离 */
  flex-wrap: wrap; /* 如果按钮太多可以换行 */
}

.dialog-footer {
  text-align: right;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-progress-circle) {
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
}

:deep(.el-skeleton) {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .study-area {
    padding: 10px;
  }
  
  .timer-controls {
    flex-direction: column;
    align-items: center;
  }
  
  .timer-controls .el-button {
    width: 200px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
}
</style>